package com.atguigu.gmall.common.interceptors;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

//RequestInterceptor： 请求拦截器（远程调用）
public class FeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {

        //1号 请求头中的用户id传递给2号
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        //判断requestAttributes是不是null，如果是null会直接空指针异常
        if (requestAttributes!= null){
            //1号对象
            HttpServletRequest request = requestAttributes.getRequest();
            if (null != request){
                //真实用户id
                String userId = request.getHeader("userId");
                if (!StringUtils.isEmpty(userId)){
                    //RequestTemplate : 即将马上发出远程调用请求对象  2号
                    requestTemplate.header("userId",userId);
                }

                //临时用户id
                String userTempId = request.getHeader("userTempId");
                if (!StringUtils.isEmpty(userTempId)){
                    //RequestTemplate : 即将马上发出远程调用请求对象  2号
                    requestTemplate.header("userTempId",userTempId);
                }
            }
        }

    }

}
